package com.tanhua.manager.service;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.domain.db.Admin;
import com.tanhua.dubbo.api.db.AdminApi;
import com.tanhua.manager.exceptions.TanhuaException;
import com.tanhua.manager.util.HttpUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {
    @DubboReference
    private AdminApi adminApi;
    //记录当前是否已经登录
    private boolean isLogin;
    //记录当前是否扫码登陆失败
    private boolean isLoginFail;
    //当前登录用户token
    private String jwtToken;

    public ResponseEntity checkLogin() {
        int flag = 1;
        while (true) {
            if (isLogin) { //如果登录状态已经登录，返回用户token
                isLogin = false; //状态复位
                return ResponseEntity.ok(this.jwtToken);
            }
            if (isLoginFail) { //扫描登录失败，返回错误信息
                return ResponseEntity.status(200).body("扫描登录失败");
            }
            try { //每500毫秒查询一下状态
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (flag > 500) {
                return ResponseEntity.status(200).body("登录超时");
            }
            flag++;
        }
    }

    public void callback(String code) throws Exception{
        System.out.println("微信服务器回调");
        if (code == null) {
            throw new TanhuaException(500, "用户禁止授权....");
        }
        try {
            //定义地址
            String token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx3bdb1192c22883f3&secret=db9d6b88821df403e5ff11742e799105&code=" + code + "&grant_type=authorization_code";
            //获取token
            //发送请求
        /*{
            "access_token":"ACCESS_TOKEN",
                "expires_in":7200,
                "refresh_token":"REFRESH_TOKEN",
                "openid":"OPENID",
                "scope":"SCOPE",
                "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
        }*/
            Map<String, Object> token_map = HttpUtils.sendGet(token_url);
            String  access_token = (String) token_map.get("access_token");
            String  openid = (String) token_map.get("openid");

            //通过openId去mysql数据库查询用户，如果没有该用户，则不允许登录
            Admin admin= adminApi.queryAdminByOpenId(openid);
            if (admin == null) {
             //   throw new TanhuaException(500, "无该用户");
            }

            //获取用户个人信息
/*        {
            "openid":"OPENID",
                "nickname":"NICKNAME",
                "sex":1,
                "province":"PROVINCE",
                "city":"CITY",
                "country":"COUNTRY",
                "headimgurl": "https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
                "privilege":[
            "PRIVILEGE1",
                    "PRIVILEGE2"
                    ],
            "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"

        }*/
            String user_url = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid;
            Map<String, Object> user_map = HttpUtils.sendGet(user_url);
            //获取微信头像地址
            String  avatar   = (String) user_map.get("headimgurl");
            System.out.println(user_map);
            //构建给前端返回的值token
            Map jwtMap = new HashMap();
            jwtMap.put("username", admin.getUsername());
            jwtMap.put("avatar", avatar);
            this.jwtToken= JwtUtils.createToken(jwtMap);
            //是否登录
            this.isLogin = true;
        } catch (Exception e) {
            this.isLoginFail = true;
        }

    }

    /**
     * 账号密码登录
     * @param username
     * @param password
     * @return
     */
    public ResponseEntity login(String username, String password) {
        //        判断用户名和密码是否为空  但凡有一个为空就不行
        if(StringUtils.isBlank(username)||StringUtils.isBlank(password)){
            throw new TanhuaException(500,"用户名或密码不能为空");
        }
        //         根据用户名查询表中的数据  select * from tb_admin where  username=??
        Admin admin = adminApi.findByUsername(username);
//          如果根据用户名查不到用户了 用户名错误 抛异常的方式告诉前端
        if(admin==null){
            throw new TanhuaException(500,"用户名错误");
        }
//          如果根据用户名查到用户了 再比较密码
        String passwordDb = admin.getPassword();
        String passwordPage = DigestUtils.md5Hex(password);
        //明文的密码要加密成密文的密码
        if(!StringUtils.equals(passwordDb,passwordPage)){
//            两个密码有可能不一样 抛异常的方式告诉前端
            throw new TanhuaException(500,"密码错误");
        }

        Map map = new HashMap();
        map.put("avatar", admin.getAvatar());
        map.put("username",admin.getUsername());
        String token = JwtUtils.createToken(map);

        Map resultMap = new HashMap();
        resultMap.put("token",token);

        return ResponseEntity.ok(resultMap);
    }

    public Admin queryAdminByUsername(String username) {
        Admin admin = adminApi.findByUsername(username);
        return admin;
    }
}
